package com.lw.yygh.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.config.filter.IFilterConfig;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lw.yygh.activemq.Produce;
import com.lw.yygh.enums.OrderStatusEnum;
import com.lw.yygh.enums.PaymentStatusEnum;
import com.lw.yygh.enums.PaymentTypeEnum;
import com.lw.yygh.exception.YyghException;
import com.lw.yygh.hosp.feign.HospFeignClient;
import com.lw.yygh.model.order.*;
import com.lw.yygh.model.user.Patient;
import com.lw.yygh.model.user.UserInfo;
import com.lw.yygh.order.mapper.OrderMapper;
import com.lw.yygh.order.service.OrderService;
import com.lw.yygh.order.service.PaymentService;
import com.lw.yygh.order.service.WeixinService;
import com.lw.yygh.result.ResultCodeEnum;
import com.lw.yygh.userClient.feign.PatientFeignClient;
import com.lw.yygh.utils.HttpRequestHelper;
import com.lw.yygh.vo.hosp.ScheduleOrderVo;
import com.lw.yygh.vo.msm.MsmVo;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderInfo> implements OrderService {
    @Autowired
    private PatientFeignClient patientFeignClient;
    @Autowired
    private HospFeignClient hospFeignClient;
    @Autowired
    private Produce produce;

    @Autowired
    private PaymentService paymentService;
    @Autowired
    private WeixinService weixinService;
    @Autowired
    private OrderMapper orderMapper;
    @Override
    public String saveOrder(String scheduleId, Long patientId) {
        //获取就诊人信息
        Patient patient = patientFeignClient.getPatientOrder( patientId );
        //获取排班相关信息
        ScheduleOrderVo scheduleOrderVo = hospFeignClient.getScheduleOrderVo( scheduleId );

        //判断当前时间是否还可以预约
        if(new DateTime(scheduleOrderVo.getStartTime()).isAfterNow()
                || new DateTime(scheduleOrderVo.getEndTime()).isBeforeNow()) {
            throw new YyghException( ResultCodeEnum.TIME_NO);
        }
        //获取签名信息
        SignInfoVo signInfoVo = hospFeignClient.getSignInfoVo( scheduleOrderVo.getHoscode() );

        //添加到订单表
        OrderInfo orderInfo = new OrderInfo();
        BeanUtils.copyProperties( scheduleOrderVo,orderInfo );
        //向orderInfo设置其他数据
        String outTradeNo = System.currentTimeMillis() + ""+ new Random().nextInt(100);
        orderInfo.setOutTradeNo(outTradeNo);
        orderInfo.setScheduleId(scheduleId);
        orderInfo.setUserId(patient.getUserId());
        orderInfo.setPatientId(patientId);
        orderInfo.setPatientName(patient.getName());
        orderInfo.setPatientPhone(patient.getPhone());
        orderInfo.setOrderStatus( OrderStatusEnum.UNPAID.getStatus());
        baseMapper.insert( orderInfo );
        //设置调用医院接口的参数
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("hoscode",orderInfo.getHoscode());
        paramMap.put("depcode",orderInfo.getDepcode());
        paramMap.put("hosScheduleId",scheduleOrderVo.getHosScheduleId());
        paramMap.put("reserveDate",new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd"));
        paramMap.put("reserveTime", orderInfo.getReserveTime());
        paramMap.put("amount",orderInfo.getAmount());
        paramMap.put("name", patient.getName());
        paramMap.put("certificatesType",patient.getCertificatesType());
        paramMap.put("certificatesNo", patient.getCertificatesNo());
        paramMap.put("sex",patient.getSex());
        paramMap.put("birthdate", patient.getBirthdate());
        paramMap.put("phone",patient.getPhone());
        paramMap.put("isMarry", patient.getIsMarry());
        paramMap.put("provinceCode",patient.getProvinceCode());
        paramMap.put("cityCode", patient.getCityCode());
        paramMap.put("districtCode",patient.getDistrictCode());
        paramMap.put("address",patient.getAddress());
        //联系人
        paramMap.put("contactsName",patient.getContactsName());
        paramMap.put("contactsCertificatesType", patient.getContactsCertificatesType());
        paramMap.put("contactsCertificatesNo",patient.getContactsCertificatesNo());
        paramMap.put("contactsPhone",patient.getContactsPhone());
        paramMap.put("timestamp", HttpRequestHelper.getTimestamp());
        paramMap.put("sign", signInfoVo.getSignKey());
        JSONObject result = HttpRequestHelper.sendRequest( paramMap,  "http://localhost:9998/order/submitOrder" );
        if (result.getInteger( "code" )==200){
            JSONObject jsonObject = result.getJSONObject("data");
            //预约记录唯一标识（医院预约记录主键）
            String hosRecordId = jsonObject.getString("hosRecordId");
            //预约序号
            Integer number = jsonObject.getInteger("number");;
            //取号时间
            String fetchTime = jsonObject.getString("fetchTime");;
            //取号地址
            String fetchAddress = jsonObject.getString("fetchAddress");;
            //更新订单
            orderInfo.setHosRecordId(hosRecordId);
            orderInfo.setNumber(number);
            orderInfo.setFetchTime(fetchTime);
            orderInfo.setFetchAddress(fetchAddress);
            baseMapper.updateById(orderInfo);
            //排班可预约数
            Integer reservedNumber = jsonObject.getInteger("reservedNumber");
            //排班剩余预约数
            Integer availableNumber = jsonObject.getInteger("availableNumber");
            //发送mq信息更新管理医院那边的号源和短信通知
            OrderMqVo orderMqVo = new OrderMqVo();
            orderMqVo.setScheduleId(scheduleId);
            orderMqVo.setReservedNumber(reservedNumber);
            orderMqVo.setAvailableNumber(availableNumber);

            //短信提示
            MsmVo msmVo = new MsmVo();
            msmVo.setPhone(orderInfo.getPatientPhone());
            String reserveDate =
                    new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd")
                            + (orderInfo.getReserveTime()==0 ? "上午": "下午");
            Map<String,Object> param = new HashMap<String,Object>(){{
                put("title", orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle());
                put("amount", orderInfo.getAmount());
                put("reserveDate", reserveDate);
                put("name", orderInfo.getPatientName());
                put("quitTime", new DateTime(orderInfo.getQuitTime()).toString("yyyy-MM-dd HH:mm"));
            }};
            msmVo.setParam(param);
            orderMqVo.setMsmVo(msmVo);
        String s = JSONObject.toJSONString( orderMqVo );
        produce.produceMsg( s );

        }else {
            throw new YyghException(result.getString("message"), ResultCodeEnum.FAIL.getCode());
        }
        return orderInfo.getOutTradeNo();
    }

    @Override
    public OrderInfo getOrder(String orderId) {
        OrderInfo orderInfo = baseMapper.selectOne( new QueryWrapper<OrderInfo>().eq( "out_trade_no",orderId ) );
        return this.packOrderInfo(orderInfo);
    }

    //查询当前用户订单并且分页
    @Override
    public IPage<OrderInfo> selectPage(Page<OrderInfo> pageParam, OrderQueryVo orderQueryVo) {
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        wrapper.eq( "user_id",orderQueryVo.getUserId() );
        //orderQueryVo获取条件值
        String name = orderQueryVo.getKeyword(); //医院名称
        Long patientId = orderQueryVo.getPatientId(); //就诊人名称
        String orderStatus = orderQueryVo.getOrderStatus(); //订单状态
        String reserveDate = orderQueryVo.getReserveDate();//安排时间
        String createTimeBegin = orderQueryVo.getCreateTimeBegin();
        String createTimeEnd = orderQueryVo.getCreateTimeEnd();
        //对条件值进行非空判断
        if(!StringUtils.isEmpty(name)) {
            wrapper.like("hosname",name);
        }
        if(!StringUtils.isEmpty(patientId)) {
            wrapper.eq("patient_id",patientId);
        }
        if(!StringUtils.isEmpty(orderStatus)) {
            wrapper.eq("order_status",orderStatus);
        }
        if(!StringUtils.isEmpty(createTimeBegin)) {
            wrapper.ge("create_time",createTimeBegin);
        }
        if(!StringUtils.isEmpty(createTimeEnd)) {
            wrapper.le("create_time",createTimeEnd);
        }
        Page<OrderInfo> orderInfoPage = baseMapper.selectPage( pageParam, wrapper );
        orderInfoPage.getRecords().stream().forEach( item->{
            this.packOrderInfo( item );
        } );
        return orderInfoPage;
    }

    //更新订单状态
    @Override
    public void updateOrder(Long id) {
        OrderInfo orderInfo = baseMapper.selectById( id );
        orderInfo.setOrderStatus( OrderStatusEnum.CANCLE.getStatus() );
        baseMapper.updateById( orderInfo );
    }
    //取消预约
    @Override
    public Boolean cancelOrder(String orderId) {
        //根据订单查询订单
        OrderInfo orderInfo = this.getOrder( orderId );
        //调用医院接口实现预约取消
        //获取签名
        SignInfoVo signInfoVo = hospFeignClient.getSignInfoVo( orderInfo.getHoscode() );
        //设置请求参数
        Map<String,Object> reqMap=new HashMap<>();
        reqMap.put("hosRecordId",orderInfo.getHosRecordId());
        reqMap.put("sign", signInfoVo.getSignKey());
        JSONObject result = HttpRequestHelper.sendRequest( reqMap, "http://localhost:9998/order/updateOrder" );
        if(result.getInteger("code") != 200) {
            throw new YyghException(result.getString("message"), ResultCodeEnum.FAIL.getCode());
        }
        //判断订单是否可以退款
        if (orderInfo.getOrderStatus().intValue()==OrderStatusEnum.PAID.getStatus().intValue()){
            //判断当前时间是否可以取消退款
            DateTime dateTime = new DateTime( orderInfo.getQuitTime() );
            if (dateTime.isBeforeNow()){
                throw new YyghException( ResultCodeEnum.CANCEL_ORDER_NO );
            }
            Boolean aBoolean = weixinService.refund( orderId );
            if (!aBoolean){
                throw new YyghException( ResultCodeEnum.CANCEL_ORDER_FAIL );
            }
            //更新支付记录状态
            PaymentInfo paymentInfo = paymentService.getPaymentInfo( orderId, PaymentTypeEnum.WEIXIN.getStatus() );
            paymentInfo.setPaymentStatus( PaymentStatusEnum.REFUND.getStatus() );
            paymentService.updateById( paymentInfo );
        }
        //更新订单状态
        orderInfo.setOrderStatus( OrderStatusEnum.CANCLE.getStatus() );
        baseMapper.updateById( orderInfo );
        //更新排班
        hospFeignClient.updateSchedule( orderInfo.getScheduleId() );

        return true;
    }


    private OrderInfo packOrderInfo(OrderInfo orderInfo) {
        orderInfo.getParam().put("orderStatusString", OrderStatusEnum.getStatusNameByStatus(orderInfo.getOrderStatus()));
        return orderInfo;
    }
}
